<script setup lang="ts">
	import { useCorps } from "./hook";
	import Refresh from "@iconify-icons/ep/refresh";
	import AddFill from "@iconify-icons/ri/add-circle-line";
  import BookmarkFill from "@iconify-icons/ri/bookmark-fill";
	import { PureTableBar } from "@/components/RePureTableBar";
	import { useRenderIcon } from "@/components/ReIcon/src/hooks";
	import { ref, reactive, onMounted, nextTick } from "vue";
  import More from "@iconify-icons/ep/more-filled";
  import { Printer, ArrowDown } from '@element-plus/icons-vue'
  import dayjs from 'dayjs';
  import { message } from "@/utils/message";
  import {
    projectReplacentApi
  } from "@/api/projectApi";
	const {
		form,
		loading,
		columns,
		dataList,
		pagination,
		isShow,
		onSearch,
		resetForm,
		handleSizeChange,
		handleCurrentChange,
		deviceDetection,
    expandColumns
	} = useCorps();
	const formRef = ref();

  const dialogProjectStatus = ref(false)
  const dialogInfo = ref()
  const dialogProjectTitle = ref()
  const seeDetail = (row) => {
    window.open(row.attachment, '_blank');
  }

  const projectTypeChange = (val) => {
    for (let item of form.taskTypeOptions) {
      item.disabled = false
    }

    if(val === 1) {
      form.taskTypeOptions[8].disabled = true;
      form.taskTypeOptions[9].disabled = true;
    }
    if(val === 4 || val === 5) {
      form.taskTypeOptions[4].disabled = true;
      form.taskTypeOptions[5].disabled = true;
    }
    if(val === 6) {
      form.taskTypeOptions[4].disabled = true;
      form.taskTypeOptions[5].disabled = true;
      form.taskTypeOptions[8].disabled = true;
      form.taskTypeOptions[9].disabled = true;
    }
  }

  const newFormInline = reactive({
    rangeHandleDate: null,
    remarks: ''
  })

  const contentRef = ref();
  const tableWidth = ref()
  onMounted(()=> {
    tableWidth.value = contentRef.value.offsetWidth
    observer.observe(contentRef.value)
  })
  const observer = new ResizeObserver(entries => {
    entries.forEach(entry => {
      tableWidth.value = entry.contentRect.width
    })
  })
  const dialogProject = ref(false)
  const dialogForm = reactive({
    projectNo: null,
    projectType: null,
    electControl: null,
    consignType: null,
    taskType: null
  })
  let handC: TableColumnList = [
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
      width: 100
    }
  ]
  const detailInfo = ref()
  let columnsCorrct = ref(columns)
  if(localStorage.getItem('id') === '1') {
    columnsCorrct.value = [...columns, ...handC]
  }
  const correctData = (row: any) => {
    dialogProject.value = true;
    detailInfo.value = row;
    dialogForm.projectNo = row.projectNo;
    dialogForm.projectType = row.projectType;
    dialogForm.electControl = row.electControl;
    dialogForm.consignType = row.consignType;
    dialogForm.taskType = row.taskType;
  }
  // 删除参数为空的键值
  function cleanEmptyData(obj: object) {
    Object.keys(obj).forEach(key => {
      if (obj[key] === null || obj[key] === '') {
        delete obj[key];
      }
    });
    return obj
  }
  const confirmDialogProject = async() => {
    const res: any = await projectReplacentApi(cleanEmptyData(dialogForm))
    if(res?.code ===200) {
      message(`操作成功`, {
        type: "success"
      });
      dialogProject.value = false;
      onSearch()
    }
  }
</script>

<template>
	<div class="main">
		<el-form ref="formRef" :inline="true" :model="form"
			class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px] overflow-auto">
			<el-form-item label="项目名称:">
				<el-input v-model="form.projectName" class="!w-[180px]" clearable placeholder="请输入项目名称" />
			</el-form-item>
      <el-form-item label="项目编号:">
      	<el-input v-model="form.projectNo" class="!w-[180px]" clearable placeholder="请输入项目编号" />
      </el-form-item>
      <el-form-item label="项目类型:">
        <el-select
          v-model="form.projectType"
          placeholder="请选择"
          class="!w-[130px]"
          clearable
          @change="projectTypeChange"
        >
          <el-option
            v-for="item in form.projectTypeOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="执行阶段:">
        <el-select
            v-model="form.taskType"
            placeholder="请选择"
            class="!w-[130px]"
            clearable
          >
            <el-option
              v-for="item in form.taskTypeOptions"
              :key="item.value"
              :label="item.name"
              :value="item.value"
              :disabled="item.disabled"
            />
          </el-select>
      </el-form-item>
      <el-form-item label="状态:">
        <el-select
          v-model="form.status"
          placeholder="请选择"
          class="!w-[100px]"
          clearable
        >
          <el-option label="未开始" :value="0" />
          <el-option label="进行中" :value="1" />
          <el-option label="已挂起" :value="2" />
          <el-option label="已完成" :value="3" />
          <el-option label="已关闭" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否电控:">
        <el-select
          v-model="form.electControl"
          placeholder="请选择"
          class="!w-[100px]"
          clearable
        >
          <el-option label="否" :value="0" />
          <el-option label="是" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="货款类型:">
        <el-select
          v-model="form.consignType"
          placeholder="请选择"
          class="!w-[100px]"
          clearable
        >
          <el-option label="发货款" :value="1" />
          <el-option label="到货款" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="交付状态:">
        <el-select
          v-model="form.isDelive"
          placeholder="请选择"
          class="!w-[100px]"
          clearable
        >
          <el-option label="未交付" :value="0" />
          <el-option label="已交付" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="收款标识:">
        <el-select
          v-model="form.receiptFull"
          placeholder="请选择"
          class="!w-[100px]"
          clearable
        >
          <el-option label="未结清" :value="0" />
          <el-option label="已结清" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="时间筛选:">
        <el-select
            v-model="form.timeType"
            placeholder="请选择"
            class="!w-[110px]"
            clearable
          >
            <el-option label="合同开始" value="startDate" />
            <el-option label="合同结束" value="endDate" />
            <el-option label="计划开始" value="planStartDate" />
            <el-option label="计划结束" value="planEndDate" />
          </el-select>
          <el-date-picker
            class="!w-[260px] ml-[5px]"
            v-model="form.rangeDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
      </el-form-item>

			<el-form-item>
				<el-button type="primary" :icon="useRenderIcon('ri:search-line')" :loading="loading" @click="onSearch">
					搜索
				</el-button>
				<el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
					重置
				</el-button>
			</el-form-item>
		</el-form>
		<div ref="contentRef" :class="['flex', deviceDetection() ? 'flex-wrap' : '']">
			<PureTableBar :class="[isShow && !deviceDetection() ? '!w-[60vw]' : 'w-full']"
				style="transition: width 220ms cubic-bezier(0.4, 0, 0.2, 1)" title=" " :columns="columnsCorrct"
				@refresh="onSearch">
        <template #title>

        </template>
				<template v-slot="{ size, dynamicColumns }">
					<pure-table ref="tableRef" showOverflowTooltip table-layout="auto"
						:loading="loading" :size="size" adaptive :adaptiveConfig="{ offsetBottom: 108 }"
						:data="dataList" :columns="dynamicColumns" :pagination="pagination" row-key="projectId"
						:paginationSmall="size === 'small' ? true : false" :header-cell-style="{background: 'var(--el-fill-color-light)',
						color: 'var(--el-text-color-primary)'}" @page-size-change="handleSizeChange" @page-current-change="handleCurrentChange">
            <template #expand="props">
              <div class="tableBox" ref="multipleTableRef" style="transform: translateZ(0);" :style="{'width': (tableWidth-20) +'px'}">
                <pure-table ref="tableRef1" showOverflowTooltip table-layout="auto" border row-key="taskId"
                  :tree-props="{ children: 'childrens', hasChildren: 'hasChildren' }" default-expand-all
                  :adaptiveConfig="{ offsetBottom: 108 }" :data="props.row.taskList" :columns="expandColumns"
                  :paginationSmall="true" :header-cell-style="{background: '#e3e3e3', color: 'var(--el-text-color-primary)'}">
                  <template #status="{row}">
                    <div>
                      <div v-if="row.status === 0">
                        <el-tag type="info">未开始</el-tag>
                      </div>
                      <div v-if="row.status === 1">
                        <el-tag type="warning">进行中</el-tag>
                      </div>
                      <div v-if="row.status === 2"><el-tag>挂起跳过</el-tag></div>
                      <div class="flex" v-if="row.status === 3">
                        <el-tag type="success" class="mr-2">已完成</el-tag>
                      </div>
                      <div v-if="row.status === 4">
                        <el-tag type="danger">已关闭</el-tag>
                      </div>
                    </div>
                  </template>
                  <template #assigneds="{row}">
                    <div class="assigneds">
                      <span v-for="(item, curr) in row.assigneds" :key="curr" class="str">
                        {{item.user?.name}}<span>, </span>
                      </span>
                      <span v-if="row.assigneds && row.assigneds.length === 0">--</span>
                    </div>
                  </template>
                  <template #assignedExtras="{row}">
                    <div class="assigneds">
                      <span v-for="(item, curr) in row.assignedExtras" :key="curr" class="str">
                        {{item.user?.name}}<span>, </span>
                      </span>
                      <span v-if="row.assignedExtras && row.assignedExtras.length === 0">--</span>
                    </div>
                  </template>
                </pure-table>
              </div>

            </template>
            <template #taskTypeName="scope">
              <span>{{scope.row.taskTypeName || '--'}}</span>
              <template v-if="scope.row.childTaskTypeName">
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  :content="scope.row.childTaskTypeName"
                  placement="top"
                >
                  <el-button :icon="useRenderIcon(BookmarkFill)" size="small" type="text" link></el-button>
                </el-tooltip>
              </template>
            </template>
            <template #surplusDate="{row}">
              <el-tag :type="row.surplusDate >0?'success':'danger'" >{{row.surplusDate || '--'}}</el-tag>
            </template>
            <template #projectType="{row}">
              <span v-if="row.projectType === 1">生产</span>
              <span v-else-if="row.projectType === 2">生产实施</span>
              <span v-else-if="row.projectType === 3">集成 (有生产)</span>
              <span v-else-if="row.projectType === 4">集成 (无生产)</span>
              <span v-else-if="row.projectType === 5">外包</span>
              <span v-else-if="row.projectType === 6">贸易</span>
              <span v-else>其他</span>
            </template>
            <template #isDelive="{row}">
              <el-tag type="success" v-if="row.isDelive === 1">已交付</el-tag>
              <el-tag type="info" v-else>未交付</el-tag>
            </template>
            <template #receiptFull="{row}">
              <el-tag type="success" v-if="row.receiptFull === 1">已结清</el-tag>
              <el-tag type="info" v-else>未结清</el-tag>
            </template>
            <template #statusName="{row}">
              <el-tag type="info" v-if="row.status === 0">{{row.statusName}}</el-tag>
              <el-tag v-else-if="row.status === 1">{{row.statusName}}</el-tag>
              <el-tag type="warning" v-else-if="row.status === 2">{{row.statusName}}</el-tag>
              <el-tag type="success" v-else-if="row.status === 3">{{row.statusName}}</el-tag>
              <el-tag type="danger" v-else-if="row.status === 4">{{row.statusName}}</el-tag>
            </template>
            <template #attachment="{row}">
              <el-button type="primary" size="small" plain @click="seeDetail(row)">查看</el-button>

            </template>
            <template #description="{row}">
              <el-tooltip placement="top" popper-style="max-width: 260px">
                <template #content> {{row.description || '--'}} </template>
                <span>描述</span>
              </el-tooltip>
            </template>
            <template #operation="{ row }">
              <el-button type="primary" @click="correctData(row)">
              	纠正
              </el-button>
            </template>
					</pure-table>
				</template>
			</PureTableBar>
		</div>
    <el-dialog
      top="4%"
      v-model="dialogProject"
      title="纠正项目数据"
      :close-on-click-modal="false"
      width="600px">
      <el-form label-width="auto">
        <el-form-item :label="'项目名称'" required>
          {{detailInfo.projectName}}
        </el-form-item>
        <el-form-item :label="'项目编号'">
        	<el-input v-model="dialogForm.projectNo" clearable placeholder="请输入项目编号" />
        </el-form-item>
        <el-form-item :label="'项目类型'" required>
          <el-select
            v-model="dialogForm.projectType"
            placeholder="请选择"

            clearable
          >
            <el-option label="生产" :value="1" />
            <el-option label="生产-实施" :value="2" />
            <el-option label="集成-有生产" :value="3" />
            <el-option label="集成-无生产" :value="4" />
            <el-option label="外包" :value="5" />
            <el-option label="贸易" :value="6" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否电控" required>
        	<el-select
        	  v-model="dialogForm.electControl"
        	  placeholder="请选择"

        	  clearable
        	>
        	  <el-option label="否" :value="0" />
        	  <el-option label="是" :value="1" />
        	</el-select>
        </el-form-item>
        <el-form-item label="货款类型" required>
        	<el-select
        	  v-model="dialogForm.consignType"
        	  placeholder="请选择"

        	  clearable
        	>
        	  <el-option label="发货款" :value="1" />
        	  <el-option label="到货款" :value="2" />
        	</el-select>
        </el-form-item>
        <el-form-item :label="'任务阶段'">
        	<el-input v-model="dialogForm.taskType" type="number" class="no_number" clearable placeholder="请输入任务阶段" />
        </el-form-item>
        <div class="flex-c w-full" style="justify-content: right;">
          <el-button @click="dialogProject = false">取消</el-button>
          <el-button type="primary" @click="confirmDialogProject">确定</el-button>
        </div>
      </el-form>
    </el-dialog>
	</div>
</template>

<style scoped lang="scss">
	.main-content {
		margin: 10px 10px 0 !important;
	}
  .assigneds {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .assigneds .str:last-child span{
    display: none;
  }
  :deep(.el-icon--right) {
    margin-left: 0;
  }
  .tableBox {
    position: sticky;
    left: 0;
    z-index: 3; /* 确保嵌套表格在主表格之上 */
  }
  .taskMyActive {
    border-color: #409eff;
    // padding: 4px 10px;
    color: #409eff;
  }
  .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: flex;
    align-items: center;
    margin-top: 6px;
  }
</style>
